/**
 * 操作日志管理组合函数
 */
import { ref, readonly } from 'vue'
import type { OperationLog } from '../types/app'

export function useOperationLog(maxLogCount: number = 50) {
  // 操作日志状态
  const operationLogs = ref<OperationLog[]>([])
  
  /**
   * 生成唯一ID
   */
  const generateId = (): string => {
    return `log_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  }

  /**
   * 添加操作日志
   */
  const addLog = (
    message: string, 
    type: OperationLog['type'] = 'info',
    details?: any
  ): void => {
    const log: OperationLog = {
      id: generateId(),
      time: new Date().toLocaleTimeString('zh-CN', {
        hour12: false,
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        fractionalSecondDigits: 3
      }),
      message,
      type,
      details
    }

    // 添加到数组开头（最新的在前面）
    operationLogs.value.unshift(log)

    // 限制日志数量，移除最旧的日志
    if (operationLogs.value.length > maxLogCount) {
      operationLogs.value = operationLogs.value.slice(0, maxLogCount)
    }

    // 在控制台也输出日志（开发模式）
    if (process.env.NODE_ENV === 'development') {
      const logMethod = type === 'error' ? console.error : 
                      type === 'warning' ? console.warn :
                      type === 'success' ? console.log : console.info
      
      logMethod(`[${log.time}] ${message}`, details ? details : '')
    }
  }

  /**
   * 添加信息日志
   */
  const addInfoLog = (message: string, details?: any): void => {
    addLog(message, 'info', details)
  }

  /**
   * 添加成功日志
   */
  const addSuccessLog = (message: string, details?: any): void => {
    addLog(message, 'success', details)
  }

  /**
   * 添加警告日志
   */
  const addWarningLog = (message: string, details?: any): void => {
    addLog(message, 'warning', details)
  }

  /**
   * 添加错误日志
   */
  const addErrorLog = (message: string, details?: any): void => {
    addLog(message, 'error', details)
  }

  /**
   * 清空所有日志
   */
  const clearLogs = (): void => {
    operationLogs.value = []
    addInfoLog('操作日志已清空')
  }

  /**
   * 根据类型过滤日志
   */
  const filterLogsByType = (type: OperationLog['type']): OperationLog[] => {
    return operationLogs.value.filter(log => log.type === type)
  }

  /**
   * 根据关键词搜索日志
   */
  const searchLogs = (keyword: string): OperationLog[] => {
    if (!keyword.trim()) {
      return operationLogs.value
    }
    
    const lowerKeyword = keyword.toLowerCase()
    return operationLogs.value.filter(log =>
      log.message.toLowerCase().includes(lowerKeyword)
    )
  }

  /**
   * 获取最近的N条日志
   */
  const getRecentLogs = (count: number): OperationLog[] => {
    return operationLogs.value.slice(0, Math.min(count, operationLogs.value.length))
  }

  /**
   * 获取统计信息
   */
  const getLogStats = () => {
    const stats = {
      total: operationLogs.value.length,
      info: 0,
      success: 0,
      warning: 0,
      error: 0
    }

    operationLogs.value.forEach(log => {
      stats[log.type]++
    })

    return stats
  }

  /**
   * 导出日志数据（用于调试或保存）
   */
  const exportLogs = (): string => {
    const logData = operationLogs.value.map(log => ({
      时间: log.time,
      类型: log.type,
      消息: log.message,
      详情: log.details
    }))

    return JSON.stringify(logData, null, 2)
  }

  /**
   * 批量添加日志（用于初始化或恢复）
   */
  const batchAddLogs = (logs: Omit<OperationLog, 'id' | 'time'>[]): void => {
    logs.forEach(logData => {
      addLog(logData.message, logData.type, logData.details)
    })
  }

  /**
   * 删除指定日志
   */
  const removeLog = (id: string): boolean => {
    const index = operationLogs.value.findIndex(log => log.id === id)
    if (index !== -1) {
      operationLogs.value.splice(index, 1)
      return true
    }
    return false
  }

  /**
   * 获取日志类型的中文名称
   */
  const getLogTypeText = (type: OperationLog['type']): string => {
    const typeMap = {
      info: '信息',
      success: '成功', 
      warning: '警告',
      error: '错误'
    }
    return typeMap[type] || '未知'
  }

  /**
   * 获取日志类型的图标
   */
  const getLogTypeIcon = (type: OperationLog['type']): string => {
    const iconMap = {
      info: 'ℹ️',
      success: '✅',
      warning: '⚠️',
      error: '❌'
    }
    return iconMap[type] || '📝'
  }

  return {
    // 响应式状态
    operationLogs: readonly(operationLogs),
    
    // 基本操作
    addLog,
    addInfoLog,
    addSuccessLog,
    addWarningLog,
    addErrorLog,
    clearLogs,
    
    // 查询和过滤
    filterLogsByType,
    searchLogs,
    getRecentLogs,
    getLogStats,
    
    // 实用工具
    exportLogs,
    batchAddLogs,
    removeLog,
    getLogTypeText,
    getLogTypeIcon
  }
}
